package com.geostar.constructionland.analyse.controller;

import com.geostar.constructionland.analyse.service.automatic.AutomaticService;
import com.geostar.constructionland.analyse.service.automatic.CoordinateFileProxy;
import com.geostar.constructionland.analyse.service.automatic.entity.CoordinateFile;
import com.geostar.constructionland.analyse.service.automatic.util.Md5Util;
import com.geostar.constructionland.common.entity.response.ServerResponse;
import com.geostar.constructionland.common.util.CpdetectorEncoding;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.nio.charset.Charset;

@Slf4j
@Controller
@RequestMapping("/coordinateFile")
@Api(value = "建设用地解析模块")
public class CoorFileController {

    @Autowired
    CoordinateFileProxy coordinateFileProxy;
    @ApiOperation(value = "文件上传解析")
    @PostMapping(value = "/parser")
    @ResponseBody
    public ServerResponse parserCoorFile(@RequestParam("file") MultipartFile file){
        if (file.isEmpty()) {
            return ServerResponse.createByErrorMessage("上传失败，文件为空！");
        }
        String fileName = file.getOriginalFilename();
        try {
            CpdetectorEncoding cpdetectorEncoding = new CpdetectorEncoding();
            /**获取文件编码*/
            Charset charsetName = cpdetectorEncoding.getFastEncoding(file.getBytes());
            if(charsetName.name().equals("x-EUC-TW")){
                charsetName = Charset.forName("GBK");
            }
            String content = new String(file.getBytes(),charsetName);
            log.info("fileName:{},fileContent:{}",fileName,content);
            CoordinateFile coordinateFile = coordinateFileProxy.proxyFileContent(content);
            return ServerResponse.createBySuccess(coordinateFile);
        } catch (IOException e) {
            e.printStackTrace();
            return ServerResponse.createByErrorMessage(e.getMessage());
        }
    }
}
